package com.sanjin.service.impl;

import com.sanjin.common.exception.BaseException;
import com.sanjin.common.result.Result;
import com.sanjin.domain.LoginUser;
import com.sanjin.domain.dto.LoginDto;
import com.sanjin.service.LoginService;
import com.sanjin.support.properties.JwtProperties;
import com.sanjin.support.utils.JwtUtil;
import com.sanjin.support.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private RedisCache redisCache;

    @Override
    public Result login(LoginDto loginDto) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginDto.getUsername(), loginDto.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if(Objects.isNull(authenticate)){
            throw new BaseException("用户名或密码错误");
        }
        //获取userid
        //这里的LoginUser 是通过了loadUserByUsername 方法return的loginUser
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        HashMap<String, Object> map = new HashMap<>();
        map.put("UserId",userId);

        //生成Jwt
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                map);
        //配置属性
        loginUser.setToken(token);

        //将完整的用户信息存入redis ,userId作为key
        redisCache.setCacheObject("login:"+userId,loginUser);


        return Result.success(loginUser);
    }
}
